<template>
  <view class="login-container">
    <h1>登录界面</h1>
    <view class="input-group">
      <input v-model="loginForm.username" placeholder="请输入用户名" clearable></input>
    </view>
    <view class="input-group">
      <input v-model="loginForm.password" type="password" placeholder="请输入密码" clearable></input>
    </view>
    <view>
      <radio-group v-model="role" @change="changeRole">
        <radio value="U">用户</radio>
        <radio value="S">司机</radio>
      </radio-group>
    </view>
    <view class="action-group" style="margin-top: 10px;">
      <button @click="handleLogin">登录</button>
    </view>
    <view class="link-group">
      <navigator url="/pages/common/register">去注册为用户</navigator>
    </view>
  </view>
</template>

<script setup>
import {ref} from 'vue';
import {getUserInfo, login} from "../api/userMG.js";

const loginForm = ref({
  username: '',
  password: ''
});
const role = ref("U")
const handleLogin = async (event) => {
  try {
    const token = await login({
      username: loginForm.value.username,
      password: loginForm.value.password
    });
    if (token === undefined && token === "") {
      // 登录失败，提示用户
      uni.showToast({title: "登录失败，用户名或密码错误"});
    }
    // 登录成功，保存token并跳转
    uni.setStorage({
      key: 'token',
      data: token,
    });

    const res = await getUserInfo()
    console.log(role.value)
    console.log(res)
    if (role.value === "U") {
      if (res.roleWbxqy === "U") {
        // 此处添加跳转逻辑，例如跳转到首页
        uni.showToast({title: "用户账号登录成功"})
        uni.switchTab({url: '/pages/user/CarRequestManage/CarRequestManage'})
      } else {
        uni.showToast({title: "非用户账号"})
        localStorage.clear()
      }
    } else {
      if (res.roleWbxqy === "S") {
        // 此处添加跳转逻辑，例如跳转到首页
        uni.showToast({title: "司机账号登录成功"})
        uni.switchTab({url: '/pages/driver/TripManagement/TripManagement'})
      } else {
        uni.showToast({title: "非司机账号"})
        localStorage.clear()
      }
    }


  } catch (error) {
    console.error('登录出错', error);
    uni.showToast({title: "登录出错，请稍后再试"});
  }
};
// 切换角色
const changeRole = (data) => {
  role.value = data.detail.value
}
</script>

<style>
.login-container {
  padding: 20px;
}

.input-group {
  margin-bottom: 20px;
}

.radio-group {
  margin-bottom: 20px;
}

.action-group {
  margin-bottom: 20px;
}

.link-group {
  text-align: center;
}
</style>
